package com.lagou.wwyan.rpc.client;

import com.lagou.wwyan.rpc.bean.RpcRequest;
import com.lagou.wwyan.rpc.bean.RpcResponse;
import com.lagou.wwyan.rpc.handler.RPCClientHandler;
import com.lagou.wwyan.rpc.sirealizer.JSONSerializer;
import com.lagou.wwyan.rpc.sirealizer.RpcDecoder;
import com.lagou.wwyan.rpc.sirealizer.RpcEncoder;
import com.lagou.wwyan.rpc.sirealizer.Serializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RPCBoot {
    private ExecutorService executorService ;
    private Serializer serializer;
    private String basePath = "/rpc/server";


    private CuratorFramework curatorFramework;
    private Map<String, Channel> clientMap = new ConcurrentHashMap<>();
    private Map<String, RPCClientHandler> handlerMap = new ConcurrentHashMap<>();


    public RPCBoot(CuratorFramework curatorFramework) throws Exception {
        this.curatorFramework = curatorFramework;
        this.executorService =  Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

        this.serializer = new JSONSerializer();

        curatorFramework.getData().usingWatcher(new RpcCuratorWatcher()).forPath(basePath);




    }


    public synchronized void createBootstrap(String url) throws InterruptedException {
        if (clientMap.containsKey(url)){
            return;
        }
        String[] split = url.split(":");
        String host = split[0];
        int port = Integer.parseInt(split[1]);
        //创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        //创建客户端启动器
        Bootstrap bootstrap = new Bootstrap();
        RPCClientHandler handler = new RPCClientHandler();
        bootstrap.group(group)
            .channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                //这里是序列化
                pipeline.addLast(new RpcEncoder(RpcRequest.class, serializer))
                        .addLast(new RpcDecoder(RpcResponse.class,serializer))
                        .addLast(handler);
            }

        });
        ChannelFuture connect = bootstrap.connect(host, port);
        Channel channel = connect.channel();
        this.clientMap.put(url,channel);
        this.handlerMap.put(url,handler);
//        connect.channel().close();
    }

    public synchronized void deleteBootstrap(String url) throws InterruptedException {
        Channel channel = clientMap.remove(url);
        handlerMap.remove(url);
        if (channel != null){
            String[] split = url.split(":");
            String host = split[0];
            int port = Integer.parseInt(split[1]);
            channel.close();
        }

    }

    public  class RpcCuratorWatcher implements CuratorWatcher{

        @Override
        public void process(WatchedEvent watchedEvent) throws Exception {
            if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected){
                List<String> strings = curatorFramework.getChildren().forPath(basePath);
                if (strings != null){
                    for (String string : strings) {
                        byte[] bytes = curatorFramework.getData().forPath(basePath + "/" + string);
                        String url = new String(bytes);
                        createBootstrap(url);
                    }
                }

            }
            curatorFramework.getData().usingWatcher(this).forPath(basePath);
            if (watchedEvent.getType() == Watcher.Event.EventType.NodeChildrenChanged){
                String path = watchedEvent.getPath();
                byte[] bytes = curatorFramework.getData().forPath(path);
                createBootstrap(new String(bytes));
            }
            /*if (watchedEvent.getType() == Watcher.Event.EventType.NodeDeleted){
                String path = watchedEvent.getPath();
                byte[] bytes = curatorFramework.getData().forPath(path);
                deleteBootstrap(new String(bytes));
            }*/
        }
    }
    private RPCClientHandler getHandler(){
        if (!handlerMap.isEmpty()){
            return handlerMap.values().parallelStream().findAny().get();
        }
        return null;
    }
    @SuppressWarnings("unchecked")
    public <T>  T createProxy(Class<T> clazz){
        return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{clazz},new InvocationHandler() {
            public Object invoke(Object o, Method method, Object[] args) throws Throwable  {
                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setRequestId(UUID.randomUUID().toString());
                rpcRequest.setClassName(clazz.getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameters(args);
                if (args != null) {
                    Class<?>[] parameterTypes = new Class[args.length];
                    for (int i = 0; i < args.length; i++) {
                        Class<?> aClass = args[i].getClass();
                        parameterTypes[i] = aClass;
                    }
                    rpcRequest.setParameterTypes(parameterTypes);
                } else {
                    rpcRequest.setParameterTypes(new Class[0]);
                }

                RpcResponse response = executorService.submit(() -> getHandler().sendRequest(rpcRequest)).get();
                return response.getData();
//            return "success";
            }
        });
    }
}
